package main.com.pyjioh.activity;

import java.util.ArrayList;

import main.com.pyjioh.core.ApodController;
import main.com.pyjioh.core.Gestures;

import main.com.pyjioh.R;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class AstropodActivity extends Activity implements
		OnGesturePerformedListener {

	private ApodController mApodController;
	private GestureLibrary mGestureLib;

	private void initialization() {
		if (mApodController == null) {
			mApodController = ApodController.getInstance();
			mApodController.setActivity(this);
			mApodController.refreshActivity();
		}
		
		mGestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);
		if (!mGestureLib.load()) {
			finish();
		}
		
		GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
		gestures.addOnGesturePerformedListener(this);		
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initialization();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.share:
			mApodController.showSelectAccountTypeDialog(new OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
				}
			});
			return true;
		case R.id.info:
			// TODO
			return true;
		}
		return false;
	}

	public void onButtonSelectDateClick(View v) {
		mApodController.showSelectDateDialog();
	}

	public void onButtonPrevClick(View v) {
		mApodController.showPrevDay();
	}

	public void onButtonNextClick(View v) {
		mApodController.showNextDay();
	}

	public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
	    ArrayList<Prediction> predictions = mGestureLib.recognize(gesture);
	    if (predictions.size() > 0) {
	        Prediction prediction = predictions.get(0);
	        if (prediction.score > 1.0) {
	        	if (prediction.name.equals(Gestures.prev))
	        		mApodController.showPrevDay();
	        	else if (prediction.name.equals(Gestures.next))
	        		mApodController.showNextDay();
	        }
	    }

	}

}
